package com.longrise.android.byjk.widget.view;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

/**
 * Created by godliness on 2017/3/8.
 */

public class FalterTextWatcher implements TextWatcher {

    private EditText mEt = null;
    private String mRegex;

    private final String DEFAULT_REGEX = "[^\u4E00-\u9FA5]";

    public FalterTextWatcher(EditText et) {
        this.mEt = et;
        this.mRegex = DEFAULT_REGEX;
    }

    public FalterTextWatcher(EditText et, String regex) {
        this.mEt = et;
        this.mRegex = regex;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        try {
            String str = editable.toString();
            String inputStr = clearLimitStr(mRegex, str);
            mEt.removeTextChangedListener(this);
            // et.setText方法可能会引起键盘变化,所以用editable.replace来显示内容
            editable.replace(0, editable.length(), inputStr.trim());
            mEt.addTextChangedListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String clearLimitStr(String regex, String str) {
        return str.replaceAll(regex, "");
    }
}
